package org.jeecg.modules.utils;

import lombok.SneakyThrows;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatGPTTalk {
    private static final String API_KEY = "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";


    public static String chatGPT(String prompt, String conversationId)  throws Exception  {
        String apiKey = API_KEY;
        String url = "https://api.openai.com/v1/chat/completions";
        String response = generateText(prompt, apiKey, url,conversationId);
        JSONObject jsonObject = new JSONObject(response);
        JSONArray choices = jsonObject.getJSONArray("choices");
        if (StringUtils.isEmpty(conversationId)){
            conversationId = jsonObject.getString("id");
        }
        JSONObject message = choices.getJSONObject(0).getJSONObject("message");
        String text = message.getString("content");

        return text;
    }


    private static String generateText(String prompt, String apiKey, String url,String conversationId) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("POST");
        connection.setConnectTimeout(5000);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + apiKey);
        connection.setRequestProperty("Conversation-Id", conversationId);
        connection.setDoOutput(true);
        String engine = "gpt-3.5-turbo";
        String text = "{\"role\": \"user\", \"content\": \""+prompt+"\"}";
        int maxTokens = 2048;
        double temperature = 0.0;
        String requestBody = "{\"model\": \"" + engine + "\", \"messages\": [" + text + "], \"max_tokens\": " + maxTokens + ", \"temperature\": " + temperature + "}";
        connection.getOutputStream().write(requestBody.getBytes(StandardCharsets.UTF_8));
        Scanner scanner = new Scanner(connection.getInputStream());
        String response = scanner.useDelimiter("\\A").next();
        scanner.close();
        return response;
    }
}
